package servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import specifications.ClientSpecification;
import ejb.ClientRepositoryBean;
import ejb.ClientRepositoryBeanLocal;
import ejb.LoginBean;
import ejb.LoginBeanLocal;
import entities.Client;

/**
 * Servlet implementation class CheckLoginBeforeBy
 */
@WebServlet("/CheckLoginBeforeBy")
public class CheckLoginBeforeBy extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	LoginBeanLocal loginBean;
	@EJB
	ClientRepositoryBeanLocal clBean;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckLoginBeforeBy() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    	HttpSession session = request.getSession();
    	if (session.getAttribute("Username")!=null)
    	{
    		Client cl= loginBean.getUser((String) session.getAttribute("Username"));
    		request.setAttribute("client", cl);
    		ArrayList<Client> childClients = clBean.getAllClientsForMasterClient(cl);
    		request.setAttribute("childClients", childClients);
    		getServletContext().getRequestDispatcher("/Order.jsp").forward(request, response);
    	}
    	else
    	{
    		response.sendRedirect("/NCProjectWeb/LoginForm.jsp");
    	}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

}
